package nix.bs.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nix.bs.domain.Category;
import nix.bs.service.CategoryService;
import nix.commons.CommonUtils;
import nix.servlet.BaseServlet;

public class AdminCategoryServlet extends BaseServlet {

	private CategoryService categoryService = new CategoryService();

	/**
	 * 查询所有
	 */
	public String findAll(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		List<Category> categoryList = categoryService.findAll();
		request.setAttribute("categoryList", categoryList);
		return "f:/bs/adminjsps/admin/category/list.jsp";
	}

	/**
	 * 添加分类
	 */
	public String add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Category category = CommonUtils.toBean(request.getParameterMap(),
				Category.class);
		category.setCid(CommonUtils.uuid());
		categoryService.add(category);
		return findAll(request, response);
	}

	/**
	 * 删除分类
	 */
	public String delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String cid = request.getParameter("cid");
		try {
			categoryService.delete(cid);
		} catch (CategoryException e) {
			request.setAttribute("msg", e.getMessage());
			return "f:/bs/adminjsps/admin/msg.jsp";
		}
		return findAll(request, response);
	}

	/**
	 * 加载分类
	 */
	public String editPre(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String cid = request.getParameter("cid");
		Category category = categoryService.load(cid);
		request.setAttribute("category", category);
		return "f:/bs/adminjsps/admin/category/mod.jsp";
	}
	
	/**
	 * 修改分类
	 */
	public String edit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Category category = CommonUtils.toBean(request.getParameterMap(), Category.class);
		categoryService.edit(category);
		return findAll(request, response);
	}
}
